
// import axios from 'axios';
import globalconst from '../../common/globalConst.js'
var global = globalconst.GlobalConst;
import {CommonSvc} from '../../service/commonsvc.js';
import LXCOM from '../../common/common.js'
import { LGXEnums } from '../../common/sysenum.js';

import graphfactory from '../../graph/graphfactory.js';
import mapview from '../../common/mapview.js'
import containergraphsvc from '../../service/containergraphsvc.js';
import {CGraphTypeUtil} from '../../graph/paintutil/graphtypeutil.js';
import utilfuncs from '../../common/tools/utilfuncs.js';
var funcs = utilfuncs.UtilFuncs;

import devicegraph from '../../graph/devicegraph.js';

class SymbolSvc {
    constructor(dataManger) {
        this.dataManger = dataManger;
        this.m_tPreMemSymbolUnitInfoLst = new Array();
        this.m_tmpMapWid = 32;
        this.m_tmpMapHgt = 32;
    }


    save() {
        var graphFileObj = {};
        var array = [];
        var symboList = pIconManager.getAllSymbol();
        for (var m in symboList) {
            let symbol = symboList[m];
            var unitObjList = symbol.getGraphUnitLst();
            for (var n in unitObjList) {
                let unitObj = unitObjList[n];
                var info = unitObj.toInfo();
                var jsonoj = info.toJson();
                array.push(jsonoj);
                console.log(obj);
            }
        }
        graphFileObj["elements"] = array;
        var version = "v0.0.0.1";
        graphFileObj["version"] = version;
        graphFileObj["mapScale"] = this.dataManger.getMapScale();
        graphFileObj["fileKind"] = 0;
        return graphFileObj;
    }

    makeSelGraphs2Symbol(mainType, symbolName, state) {
        var tSelGraphLst = this.dataManger.getSelGraphs();
        var errMsg = ""
        var symbolConflict = false;
        var maxIdx = 0;
        var destTypeID = 0;
        var pIconManager = this.dataManger.getSymbolManager();
        var symboLst = pIconManager.getAllSymbol();
        for (let i = 0; i < symboLst.length; i++) {
            var pIcon = symboLst[i];
            var type = pIcon.getTypeID();
            if (type >> 16 == mainType) {
                var idx = type & 0x0000ffff;
                maxIdx = Math.max(idx, maxIdx);
            }

            if (pIcon.getName() == symbolName && destTypeID == 0) {
                destTypeID = type;
            }

            if (pIcon.getName() == symbolName
                && pIcon.getState() == state) {
                errMsg = "symbolName conflict!";
                symbolConflict = true;
                break;
            }
        }
        var symbolCnt = null;
        var newSymbolID = -1;
        if (!symbolConflict) {
            if (destTypeID) {
                newSymbolID = destTypeID;
            }
            else {
                newSymbolID = mainType;
                newSymbolID = (newSymbolID << 16) | (maxIdx + 1);
            }
            symbolCnt = this.makeSelGraphs2DstSymbol(tSelGraphLst, newSymbolID, symbolName, state);
        }

        var symbolid = newSymbolID;
        return { symbolid, errMsg, sx: symbolCnt.x, sy: symbolCnt.y };
    }

    makeSelGraphs2DstSymbol(tSelGraphLst, newSymbolID, symbolName, state) {
        console.log("makeSelGraphs2DstSymbol");
        this.m_tPreMemSymbolUnitInfoLst.length = 0;
        var pIconManager = this.dataManger.getSymbolManager();
        var mapscale = this.dataManger.getMapScale();
        var scaling = this.dataManger.getScaling();
        var cntPt = new LXCOM.LGXPoint();
        var findCnt = this.calculateSymboCnt(tSelGraphLst, cntPt);
        let leawireCount = 0;
        if (!findCnt) {
            let validList = [];//排除作为引线作用的连接线，生成图形时它是独立图形对象
            tSelGraphLst.forEach(p => {
                if (p.m_graphType == LGXEnums.LGXGraphType.LineGraph_type && p.getSymbolLeadwireFlag()) {
                    leawireCount++;
                }
                else {
                    validList.push(p);
                }
            });
            var rect = CommonSvc.calGraphsZone(validList);
            cntPt = rect.getCnt();
        }
        var offset = new LXCOM.LGXPoint();
        offset.setVal(-cntPt.x, -cntPt.y);
        for (let i = 0; i < tSelGraphLst.length; i++) {
            var pGraph = tSelGraphLst[i];
            var pInfo = pGraph.toInfo();
            if (pInfo) {
                var pGraphInfo = pInfo;
                pGraphInfo.superID = newSymbolID;
                pGraphInfo.sSymbolName = symbolName;
                if (pGraph.m_graphType != LGXEnums.LGXGraphType.TerminalGraph_type) {
                    pGraphInfo.state = state;
                }
                else {
                    pGraphInfo.state = -1;
                }
                var pValidInfo = pInfo.cloneCopy();
                pValidInfo.translate(offset.x, offset.y);
                pIconManager.addSymbolInfo(pValidInfo);
                this.m_tPreMemSymbolUnitInfoLst.push(pValidInfo);
                pInfo = null;
            }
        }


        this.m_tAllSymbolDefLst
        pIconManager.endInitSymbol(this.dataManger.getAllSymbolDefLst());
        return cntPt;
    }

    translateFill(srcGraph, tx, ty) {
        if (!funcs.isBaseUnit(srcGraph.getType())
            && srcGraph.m_graphType != LGXEnums.LGXGraphType.Path_type) {
            return;
        }

        let srcFill = srcGraph.getFillDef();
        if (srcFill.gradientInfo) {
            let transSrcStPt = { x: srcFill.gradientInfo.stPt.x + tx, y: srcFill.gradientInfo.stPt.y + ty };
            let transSrcEndPt = { x: srcFill.gradientInfo.endPt.x + tx, y: srcFill.gradientInfo.endPt.y + ty };
            srcFill.setStopPos("st", transSrcStPt);
            srcFill.setStopPos("end", transSrcEndPt);
        }
    }

    calculateSymboCnt(tSelGraphLst, cntPt) {
        var flag = false;
        for (var idx in tSelGraphLst) {
            var graph = tSelGraphLst[idx];
            if (graph.m_graphType == LGXEnums.LGXGraphType.CoordFrame_type) {
                var pos = graph.getPos();
                cntPt.x = pos.nx;
                cntPt.y = pos.ny;
                flag = true;
                break;
            }
        }
        return flag;
    }

    generateAllICON() {
        let tHaveIconSymbolLst = new Array();
        var pIconManager = this.dataManger.getSymbolManager();
        var symboLst = pIconManager.getAllSymbol();
        for (let i = 0; i < symboLst.length; i++) {
            var pIcon = symboLst[i];
            var type = pIcon.getTypeID();
            if (tHaveIconSymbolLst.indexOf(type) == -1) {
                let rst = this.generateICON(type, true);
                if (rst != null)
                    tHaveIconSymbolLst.push(type);
            }
        }
        console.log(tHaveIconSymbolLst);
        return tHaveIconSymbolLst;
    }

    generateICON(symbolid, saveImmediately) {
        let graphLst = this.createTempGraph(symbolid);
        if (!graphLst) {
            return null;
        }
        let graph = graphLst[0];
        let graphZone = graph.getZone();
        this.m_tmpMapWid = graphZone.width() + 8;
        this.m_tmpMapHgt = graphZone.height() + 8;
        let tempCanvas = document.createElement("canvas");
        tempCanvas.setAttribute("width", this.m_tmpMapWid);
        tempCanvas.setAttribute("height", this.m_tmpMapHgt);
        let tmpDisMap = tempCanvas.getContext('2d');
        let iconURL = this.generateGraphICON(symbolid, graphLst, tmpDisMap, tempCanvas, saveImmediately);
        return iconURL;
    }

    generateICON_local() {
        let graph = this.dataManger.getCurentGraph();
        if (!graph) {
            return;
        }
        let graphLst = [];
        graphLst.push(graph);
        let symbolid = graph.getType();
        let graphZone = graph.getZone();
        this.m_tmpMapWid = graphZone.width() + 8;
        this.m_tmpMapHgt = graphZone.height() + 8;
        let tempCanvas = document.createElement("canvas");
        tempCanvas.setAttribute("width", this.m_tmpMapWid);
        tempCanvas.setAttribute("height", this.m_tmpMapHgt);
        let tmpDisMap = tempCanvas.getContext('2d');
        let iconURL = this.generateGraphICON(symbolid, graphLst, tmpDisMap, tempCanvas, false);
        return iconURL;
    }


    generateGraphICON(symbolid, graphLst, paintMap, tempCanvas, saveImmediately) {
        console.log("generateGraphICON***************************");
        paintMap.clearRect(0, 0, this.m_tmpMapWid, this.m_tmpMapHgt);
        var worldRect = new LXCOM.LGXRect(0, this.m_tmpMapHgt, this.m_tmpMapWid, 0);//当前视口区域
        let mapViewInfo = new mapview.MapViewParam(this.m_tmpMapWid, this.m_tmpMapHgt, worldRect);
        mapViewInfo.paintForGenerateICON = true;
        let graph = graphLst[0];
        let graphZone = graph.getZone();
        let scalex = (this.m_tmpMapWid - 6) / graphZone.width();
        let scaley = (this.m_tmpMapHgt - 6) / graphZone.height();
        let scale = Math.min(scalex, scaley);
        let midPt = graphZone.getCnt();
        mapViewInfo.paintForGenerateLineWidth = Math.ceil(1 / scale);
        mapViewInfo.paintForGenerateICON = true;

        let dstx = midPt.x - this.m_tmpMapWid / 2;
        let dsty = midPt.y - this.m_tmpMapHgt / 2;
        graph.translate({ x: -dstx, y: -dsty }, 1, false);

        let preLineSef = null;//graph.getLineDef();
        if (!preLineSef) {
            preLineSef = new LXCOM.LGXLineDefInfo();
        }
        let tempLineInfo = new LXCOM.LGXLineDefInfo();
        tempLineInfo.clone(preLineSef);
        tempLineInfo.color.setVal(0, 0, 0);
        // graph.setLineDef(tempLineInfo);

        paintMap.save();
        // paintMap.translate(midPt.x, midPt.y);
        paintMap.scale(scale, scale);
        // paintMap.translate(-midPt.x, -midPt.y);
        for (let i = 0; i < graphLst.length; i++) {
            let graph = graphLst[i];
            graph.display(paintMap, mapViewInfo);
        }

        var image = paintMap.getImageData(0, 0, this.m_tmpMapWid, this.m_tmpMapHgt);
        let iconURL = this.getImage2UpdateICON(tempCanvas, symbolid, saveImmediately);
        this.downloadICON(symbolid, tempCanvas);
        paintMap.restore();
        graph.translate({ x: dstx, y: dsty }, 1, false);
        // graph.setLineDef(preLineSef);
        return iconURL;
    }

    downloadICON(symbolid, canvas) {
        let imagedata = canvas.toDataURL("image/png");
        //imagedata = imagedata.replace(/^data:image\/(png|jpg);base64,/, "");
        console.log(imagedata);

        var oA = document.createElement("a");
        let hexString = symbolid.toString(16); // 转换为16进制字符串
        oA.download = "0x0" + hexString + '.png';// 设置下载的文件名，默认是'下载'
        oA.href = imagedata;
        document.body.appendChild(oA);
        oA.click();
        oA.remove(); // 下载之后把创建的元素删除
    }

    createTempGraph(symbolid) {
        let graphLst = [];
        let type = CGraphTypeUtil.getType32(symbolid);
        let mapCntPos = new LXCOM.LGXPoint();
        mapCntPos.setVal(this.m_tmpMapWid / 2, this.m_tmpMapHgt / 2);
        if (type == LGXEnums.LGXGraphType.MoldGraph_type) {
            let symbol = this.dataManger.getSymbol(symbolid, 0);
            if (symbol) {
                let tempGraph = graphfactory.GraphFactory.createGraphByType32(symbolid, symbol);
                if (tempGraph) {
                    tempGraph.setSymbol(symbol);
                    tempGraph.setPos(mapCntPos);
                    tempGraph.calScope(1);
                    graphLst.push(tempGraph);
                }
            }
        }
        else if (type == LGXEnums.LGXGraphType.Combine_type) {
            graphLst = containergraphsvc.ContainerGraphSvc.createTemp(this.dataManger, symbolid, mapCntPos);
        }
        else if (type == LGXEnums.LGXGraphType.LineGraph_type) {
            //线类图符，临时用一个模具图形来代替以生成图标
            let symbol = this.dataManger.getSymbol(symbolid, 0);
            if (symbol) {
                let tempGraph = new devicegraph.DeviceGraph(symbolid);
                if (tempGraph) {
                    tempGraph.setSymbol(symbol);
                    tempGraph.setPos(mapCntPos);
                    tempGraph.calScope(1);
                    graphLst.push(tempGraph);
                }
            }
        }

        return graphLst;
    }

    getImage2UpdateICON(paintMap, symbolid, saveImmediately) {
        let imagedata = paintMap.toDataURL("image/png");
        if (saveImmediately) {
            let symbolInfo = { typeID: symbolid, name: "", iconURL: imagedata };
            this.updateICON2DB(symbolInfo);
        }
        return imagedata;
    }


    updateICON2DB = function (symbolInfo) {
        var url = "api/symbol/updateICON";
        var postObj = {};
        postObj["name"] = symbolInfo.name;
        postObj["typeID"] = symbolInfo.typeID;
        postObj["userid"] = "system";
        postObj["iconURL"] = symbolInfo.iconURL;
        this.post2SaveSymbol(url, postObj);
    }

    post2SaveSymbol = function (url, obj) {
        axios.post(url, obj).then(res => {
            console.log(res.data);
        }).catch(function (error) {
            console.log(error);
        })
    }
}

export default { SymbolSvc }